package com.iraeta.service.iraorder.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.iraeta.dao.iraorder.IraorderwuliuproductDao;
import com.iraeta.entity.Iraorderwuliuproduct;
import com.iraeta.entity.vo.IraOrderWuLiuProductVo;
import com.iraeta.service.iraorder.IraorderwuliuproductService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class IraorderwuliuproductServiceImpl implements IraorderwuliuproductService {
    @Resource
    IraorderwuliuproductDao iraorderwuliuproductDao;

    @Override
    public void addIraorderwuliuproduct(Iraorderwuliuproduct iraorderwuliuproduct) {
        iraorderwuliuproductDao.insert(iraorderwuliuproduct);
    }

    @Override
    public void updateIraorderwuliuproduct(Iraorderwuliuproduct iraorderwuliuproduct) {
        iraorderwuliuproductDao.updateByPrimaryKey(iraorderwuliuproduct);
    }

    @Override
    public void deleteIraorderwuliuproduct(Integer id) {
        iraorderwuliuproductDao.deleteByPrimaryKey(id);
    }

    @Override
    public Iraorderwuliuproduct getIraorderwuliuproduct(Integer id) {
        return iraorderwuliuproductDao.selectByPrimaryKey(id);
    }

    @Override
    public List<IraOrderWuLiuProductVo> listIraorderwuliuproduct(Integer orderId, Integer wuLiuId) {
        return iraorderwuliuproductDao.selectByWuliuId(orderId, wuLiuId);
    }

    @Transactional
    @Override
    public void updateIraorderwuliuproduct(Integer wuLiuId, JSONArray wuLiuProductList) {
        for(int i=0;i<wuLiuProductList.size();i++){
            JSONObject stepJSONObject = wuLiuProductList.getJSONObject(i);
            int productId = stepJSONObject.getIntValue("id");
            int shuLiang = stepJSONObject.getIntValue("shuLiang");
            Iraorderwuliuproduct iraorderwuliuproduct = iraorderwuliuproductDao.selectByCondition(wuLiuId, productId);
            if(iraorderwuliuproduct == null) {
                iraorderwuliuproduct = new Iraorderwuliuproduct(wuLiuId, productId, shuLiang);
                iraorderwuliuproductDao.insert(iraorderwuliuproduct);
            }else{
                iraorderwuliuproduct.setShuliang(shuLiang);
                iraorderwuliuproductDao.updateByPrimaryKey(iraorderwuliuproduct);
            }
        }
    }
}
